<!--
 * @Author: 冕上 cxm66888@163.com
 * @Date: 2025-01-01 00:00:00
 * @LastEditors: 冕上 cxm66888@163.com
 * @LastEditTime: 2025-08-06 17:49:56
 * @Description: 分类管理
 * 
 * Copyright (c) 2025 by xiaoMing.Cao, All Rights Reserved. 
-->
<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="success" icon="Plus" @click="handleCreate">新增分类</el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading..." border fit highlight-current-row>
      <el-table-column align="center" label="排序" prop="sort" width="95"></el-table-column>
      <el-table-column label="分类名称" align="center">
        <template #default="scope">
          <span class="category-name">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="礼品数量" align="center" width="120">
        <template #default="scope">
          <el-tag :type="scope.row.giftCount > 0 ? 'success' : 'info'">
            {{ scope.row.giftCount }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" width="180">
        <template #default="scope">
          {{ scope.row.createdTime }}
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center">
        <template #default="scope">
          <span class="category-description">{{ scope.row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)" :disabled="scope.row.giftCount > 0">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑分类弹窗 -->
    <el-dialog v-model="showDialog" :title="isEdit ? '编辑分类' : '新增分类'" width="500px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" placeholder="请输入排序值" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="2" placeholder="请输入分类描述" maxlength="100" show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog v-model="showDeleteDialog" title="删除分类" width="400px" :close-on-click-modal="false">
      <div class="delete-confirm">
        <el-icon class="warning-icon"><Warning /></el-icon>
        <p>
          确定要删除分类 "
          <strong>{{ selectedCategoryName }}</strong>
          " 吗？
        </p>
        <p class="warning-text">删除后无法恢复，请谨慎操作！</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDeleteDialog = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Warning } from '@element-plus/icons-vue';
  import { getGiftCategories, createGiftCategory, updateGiftCategory, deleteGiftCategory } from '@/api/gift';

  const list = ref([]);
  const listLoading = ref(true);
  const showDialog = ref(false);
  const showDeleteDialog = ref(false);
  const formRef = ref(null);
  const isEdit = ref(false);
  const selectedCategoryId = ref('');
  const selectedCategoryName = ref('');

  const form = reactive({
    name: '',
    sort: 0,
    description: ''
  });

  const rules = {
    name: [
      { required: true, message: '请输入分类名称', trigger: 'blur' },
      { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
    ],
    sort: [{ required: true, message: '请输入排序值', trigger: 'blur' }]
  };

  const getList = async () => {
    listLoading.value = true;
    try {
      const response = await getGiftCategories();
      if (response.code === 200) {
        list.value = response.data.list;
      }
    } catch (error) {
      console.error('获取分类列表失败:', error);
      ElMessage.error('获取分类列表失败');
    } finally {
      listLoading.value = false;
    }
  };

  const handleCreate = () => {
    isEdit.value = false;
    form.name = '';
    form.sort = 0;
    form.description = '';
    showDialog.value = true;
  };

  const handleUpdate = row => {
    isEdit.value = true;
    selectedCategoryId.value = row._id;
    form.name = row.name;
    form.sort = row.sort;
    form.description = row.description;
    showDialog.value = true;
  };

  const handleDelete = row => {
    if (row.giftCount > 0) {
      ElMessage.warning('该分类下还有礼品，无法删除');
      return;
    }
    selectedCategoryId.value = row._id;
    selectedCategoryName.value = row.name;
    showDeleteDialog.value = true;
  };

  const submitForm = async () => {
    if (!formRef.value) return;

    await formRef.value.validate(async valid => {
      if (valid) {
        try {
          let response;
          if (isEdit.value) {
            response = await updateGiftCategory(selectedCategoryId.value, {
              name: form.name,
              sort: form.sort,
              description: form.description
            });
          } else {
            response = await createGiftCategory({
              name: form.name,
              sort: form.sort,
              description: form.description
            });
          }

          if (response.code === 200) {
            ElMessage.success(isEdit.value ? '更新成功' : '创建成功');
            showDialog.value = false;
            getList();
          } else {
            ElMessage.error(response.msg || '操作失败');
          }
        } catch (error) {
          console.error('提交失败:', error);
          ElMessage.error('提交失败');
        }
      }
    });
  };

  const confirmDelete = async () => {
    try {
      const response = await deleteGiftCategory(selectedCategoryId.value);
      if (response.code === 200) {
        ElMessage.success('删除成功');
        showDeleteDialog.value = false;
        getList();
      } else {
        ElMessage.error(response.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除分类失败:', error);
      ElMessage.error('删除失败');
    }
  };

  onMounted(() => {
    getList();
  });
</script>

<style scoped>
  .filter-container {
    padding-bottom: 10px;
  }

  .filter-item {
    margin-right: 10px;
  }

  .category-name {
    font-weight: bold;
    color: #303133;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }

  .delete-confirm {
    text-align: center;
    padding: 20px 0;
  }

  .warning-icon {
    font-size: 48px;
    color: #e6a23c;
    margin-bottom: 16px;
  }

  .warning-text {
    color: #f56c6c;
    font-size: 14px;
    margin-top: 8px;
  }
</style>
